;;; write.scm -- write Joy expressions.
;;; Copyright © 2016 Eric Bavier <bavier@member.fsf.org>
;;;
;;; Joy is free software; you can redistribute it and/or modify it under
;;; the terms of the GNU General Public License as published by the Free
;;; Software Foundation; either version 3 of the License, or (at your
;;; option) any later version.
;;;
;;; Joy is distributed in the hope that it will be useful, but WITHOUT
;;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
;;; or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
;;; License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with Joy.  If not, see <http://www.gnu.org/licenses/>.

(define-module (language joy write)
  #:use-module (srfi srfi-1)
  #:use-module (ice-9 match)
  #:export (write-joy))

(define* (write-joy expression #:optional (port (current-output-port)))
  "Write Joy expression EXPRESSION to port PORT."
  (define (print v)
    (match v
      ((? null? x)
       (display "[]"))
      ((? char? x)
       (display "'") (write-char x))
      (((? char? x) ...)
       (display "\"")
       (for-each write-char x)
       (display "\""))
      ((x xs ...)
       (display "[")
       (print x)
       (for-each (lambda (x)
  		   (display " ")
  		   (print x))
  		 xs)
       (display "]"))
      (else
       (display v))))

  (with-output-to-port port
    (lambda ()
      (print expression)
      (newline))))
